// store.js - store/retreive user moves
//

chess_spider.stores = {

'initall': function() {
	for( var source in chess_spider.stores ) {
		// only interested in real stores
		if( typeof chess_spider.stores[source] != 'object' ) continue;
		// initialize
		chess_spider.stores[source].init();
	}
},

// array of active stores
'source_arr': function() {
	var arr = new Array();
	for( var source in chess_spider.stores ) {
		// only interested in real stores
		if( typeof chess_spider.stores[source] != 'object' ) continue;
		// initialize
		if( chess_spider.stores[source].enabled ) arr.push( source );
	}
	return arr;
},

// localStore  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
'localStore': {

	'enabled' : false,
	'description':	'on the Browser (localStore)',

	// localStore initialize
	'init': function() {

		// initialize localStore
		if( window.localStorage ) {
			this.enabled = true;
			this.localIdx = window.localStorage.idx;
			// if exists, parse
			if( this.localIdx ) {
				this.localIdx = JSON.parse(this.localIdx);
			}
			// if not exists, init
			else {
				this.localIdx = new Array();
				localStorage.idx = JSON.stringify(this.localIdx);
			}
		}

		else	this.enabled = false;
	},

	// localStore save
	'save' : function( url, title, data ) {

		// put into database
		//-console.log( "writing into localStore: url="+url+", title="+title );

		// index - update if existent, otherwise add
		for( var i=0; i<this.localIdx.length; i++ )
		if( this.localIdx[i].url == url && this.localIdx[i].title == title ) {
			this.localIdx[i].access_ct++;
			this.localIdx[i].access_ts = new Date();
			var idx = this.localIdx[i].idx;
			break;
		}
		if( i >= this.localIdx.length ) {
			var idx = Math.floor( Math.random() * 4294967296);
			this.localIdx.push( { 'url': url, 'title': title, 'access_ct': 0, 'access_ts': new Date(), 'idx': idx } );
		}

		// store idx and data
		//-console.log( "writing idx: "+JSON.stringify(this.localIdx) );
		window.localStorage.idx = JSON.stringify(this.localIdx);
		window.localStorage['data_'+idx] = data;
	},

	// list of saves for this url
	'pullList': function( url, callback ) {

		//-console.log( "localStore pullList: url="+url );

		// not enabled, empty list
		if( !this.enabled || !this.localIdx.length ) {
			callback( 'localStore', new Array() );
			return;
		}

		// look for any with same url
		var arr = new Array();
		for( var i=0; i<this.localIdx.length; i++ )
		if( this.localIdx[i].url == url ) {
			var row = this.localIdx[i];
			row.source = 'localStore';
			arr.push( row );
		}

		//-console.log( 'list count: '+arr.length );
		callback( 'localStore', arr );
	},

	// pull saved record
	'pull': function( row, callback ) {

		//-console.log( 'pulling from localStore' );

		// find passed row in localIdx
		for( var i=0; i<this.localIdx.length; i++ ) {
			if( this.localIdx[i].idx == row.idx ) break;
		}
		// not found row
		if( i >= this.localIdx.length ) throw( 'did not find row' );

		// update idx
		this.localIdx[i].access_ct++;
		this.localIdx[i].access_dt = new Date().format();
		window.localStorage.idx = JSON.stringify(this.localIdx);

		// return record itself
		//-console.log( 'data: '+window.localStorage[ 'data_' + this.localIdx[i].idx ] );
		callback( 'localStore', window.localStorage[ 'data_' + this.localIdx[i].idx ] );
	}
},


// webSQL  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
'webSQL' : {

	'enabled': false,
	'description':	'on the Browser (webSQL)',

	// webSQL initialize
	'init': function() {

		// no db
		if( typeof window.openDatabase != 'function' ) {
			this.enabled = false;
			return;
		}

		// open db and add user_data table
		//-console.log( 'webSQL: init db and user_data table' );
		this.db = openDatabase( 'cs__save', 1.0, 'Chess Spider User Data', 50000 );
		if( this.db ) {
			// (re)creaate user_data table
			// todo: versioning
			this.db.transaction( function(tx) { tx.executeSql(
				"create table user_data( title unique, url, access_ts, access_ct, data )") } );
			this.enabled = true;
		}
		else	this.enabled = false;
	},

	// webSQL save
	'save': function( url, title ) {

		// put into database
		//-console.log( "insert into user_data values( "+title+', '+url+', '+new Date().format()+', 0, '+data+" )" );

		// we insert - if duplicate will bounce - sail on
		this.db.transaction( function(tx) { tx.executeSql( 
			"insert into user_data values( ?, ?, ?, ?, ? )", [ title, url, new Date().format(), 0, data ]
		) } );

		// update - even if just inserted
		this.db.transaction( function(tx) { tx.executeSql( 
			"update user_data set access_ts=?, access_ct=access_ct+1, data=? where title=?", [ new Date().format(), data, title ]
		) } );
	},

	// list of stores for this url
	'pullList': function( url, callback ) {

		//-console.log( "webSQL pullList: url="+url );

		// not enabled, empty list
		if( !this.enabled ) return new Array();

		// pull from db
		query = "select title, url, access_ts, access_ct, 'webSQL' as source from user_data "
				+ ( (url) ? "where url='"+url+"'" : '' )
				+ " order by access_ts desc";
		//-console.log( 'webSQL pull from db: '+query );
		this.db.transaction( function(tx) { tx.executeSql( query, [], function(tx,results) {
			var local_arr = new Array();
			for( var i=0; i<results.rows.length; i++ ) local_arr.push( results.rows.item(i) );
			callback( 'webSQL', local_arr );
		}) } );
	},

	// pull saved record
	'pull': function( row, callback ) {

		//-console.log( 'pulling from webSQL' );

		// pull row; callback
		this.db.transaction( function(tx) { tx.executeSql(
			"select * from user_data where title=?",
			[row.title],
			function(tx,results) { callback( 'webSQL', results.rows.item(0).data ); }
		) } );

		// inc count, set access
		this.db.transaction( function(tx) { tx.executeSql(
			"update user_data set access_ct=access_ct+1, access_dt=? where title=?",
			[ new Date().format(), row.title ],
			null
		) } );
	}
},


// server  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
'server': {

	'enabled': false,
	'description':	'on the Server (best)',

	// server initialize
	'init': function() {
		// this will be set to true when user loaded
		this.enabled = false;
	},

	// server save
	'save': function( url, title ) {

		// send message to server
		new chess_spider.Message( 'save', { 'title': title, 'url': url }, { 'data' : data }, function( message ) {
			// on success
			chess_spider.ud_id = message.result.ud_id;
			nonblockAlert( 'successfully saved to server' );
		}, null );
	
		// put into server
		//-console.log( "writing into server: url="+url+", title="+title );
	},

	// list of stores for this url
	'pullList': function( url, callback ) {

		// not enabled
		if( !this.enabled ) callback( 'server', new Array() );

		// ask server for list
		else new chess_spider.Message( 'pull', {'url':url}, null, function(message) {
			callback( 'server', message.result.rows );
		} );
	},

	// pull saved record
	'pull': function( row, callback ) {
		new chess_spider.Message( 'pull', {'ud_id':row.ud_id}, null, function(message) { callback('server',message.result.row.data); } );
	}
}

}



